import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Index',
    component: () => import('../views/Index.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/explore',
    name: 'Explore',
    component: {
      async created() {
        try {
          const res = await axios.get('/api/writers/random')
          const randomId = res.data.id
          this.$router.replace(`/experience/${randomId}?mode=random`)
        } catch (err) {
          console.error('获取随机作家失败：', err)
          this.$router.replace('/home ')
        }
      },
      render: h => h() 
    }
  },
  {
    path: '/experience/:id',
    name: 'Experience',
    component: () => import('../views/Experience.vue'),
    props: route => ({ 
      id: route.params.id,
      isRandom: route.query.mode === 'random' 
    })
  },
  
  {
    path: '/home/:id?',
    name: 'Home',
    component: () => import('../views/Home.vue'),
  },
  {
    path: '/works',
    name: 'AllWorks',
    component: () => import('../views/Works.vue')
  },
  {
    path: '/works/:writerId',
    name: 'Works',
    component: () => import('../views/Works.vue')
  },
  {
    path: '/quotes',
    name: 'AllQuotes',
    component: () => import('../views/Quotes.vue')
  },
  {
    path: '/quotes/:writerId?',
    name: 'Quotes',
    component: () => import('../views/Quotes.vue')
  },
  {
    path: '/edit-quote/:id?',
    name: 'EditQuote',
    component: () => import('../views/EditQuote.vue'),
    meta: { 
      requiresAuth: true,
      noCache: true,
      keepAlive: false 
    }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/User.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/edit-work/:id?',
    name: 'EditWork',
    component: () => import('../views/EditWork.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/edit-writer/:id?',
    name: 'EditWriter',
    component: () => import('../views/EditWriter.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/colorful-egg',
    name: 'ColorfulEgg',
    component: () => import('../views/ColorfulEgg.vue'),
    meta: {
      isHidden: true
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
